package com.alibaba.dubbo.dynamic.utils;

import com.alibaba.dubbo.common.utils.IOUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by wuyu on 2016/9/8.
 */
public class HttpUtil {

    public static String download(String url, String outDir) throws IOException {

        URLConnection urlConnection = new URL(url).openConnection();
        String attachment = urlConnection.getHeaderField("attachment");
        if(attachment==null){
            attachment=url.substring(url.lastIndexOf("/"));
        }
        InputStream inputStream = urlConnection.getInputStream();
        String fileName = outDir + "/" + attachment;
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        IOUtils.write(inputStream, fileOutputStream);
        fileOutputStream.close();
        inputStream.close();

        return fileName;
    }
}
